package com.blue.http.filter;

import com.blue.http.message.HttpRequest;
import com.blue.http.message.HttpResponse;
import com.blue.http.message.UploadFile;
import com.blue.http.util.HttpException;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Map;

/**
 * 上传临时文件清除过滤器
 *
 * @author Jin Zheng
 * @date 2018-10-29
 */
public class UploadFilter implements Filter
{
	private static Logger logger = LoggerFactory.getLogger(UploadFilter.class);

	public UploadFilter()
	{
	}

	@Override
	public void afterHandle(HttpRequest request, HttpResponse response, Exception e) throws HttpException
	{
		Map<String, UploadFile> fileMap = request.getFileMap();
		if (fileMap == null || fileMap.isEmpty())
			return;

		for (Map.Entry<String, UploadFile> entry : fileMap.entrySet())
		{
			UploadFile uploadFile = entry.getValue();
			if (uploadFile == null)
				continue;

			File file = uploadFile.getFile();
			if (file == null)
				continue;

			boolean result = FileUtils.deleteQuietly(file);
			String strResult = result ? "成功" : "失败";
			logger.info("删除文件：{} - {}", strResult, uploadFile);
		}
	}

}
